using Microsoft.AspNetCore.Http;
using Microsoft.EntityFrameworkCore;
using UniversalAdmin.Infrastructure.Data.Contexts;

namespace UniversalAdmin.Api.Middleware
{
    public class UserActivityMiddleware
    {
        private readonly RequestDelegate _next;
        private readonly ILogger<UserActivityMiddleware> _logger;

        public UserActivityMiddleware(RequestDelegate next, ILogger<UserActivityMiddleware> logger)
        {
            _next = next;
            _logger = logger;
        }

        public async Task InvokeAsync(HttpContext context, AdminDbContext dbContext)
        {
            // 先执行下一个中间件
            await _next(context);

            // 检查是否是已认证用户且不是排除的路径
            if (context.User?.Identity?.IsAuthenticated == true &&
                context.Request.Path.StartsWithSegments("/api", StringComparison.OrdinalIgnoreCase) &&
                !context.Request.Path.StartsWithSegments("/api/static", StringComparison.OrdinalIgnoreCase) &&
                !context.Request.Path.StartsWithSegments("/api/system/logs", StringComparison.OrdinalIgnoreCase) &&
                !context.Request.Path.StartsWithSegments("/api/files/preview", StringComparison.OrdinalIgnoreCase) &&
                !context.Request.Path.StartsWithSegments("/api/users/avatar", StringComparison.OrdinalIgnoreCase) &&
                !context.Request.Path.StartsWithSegments("/api/files/download", StringComparison.OrdinalIgnoreCase))
            {
                try
                {
                    var userIdClaim = context.User.FindFirst("UserId");
                    if (userIdClaim != null && Guid.TryParse(userIdClaim.Value, out var userId))
                    {
                        // 同步更新用户活动时间（避免DbContext被释放的问题）
                        try
                        {
                            var user = await dbContext.AppUsers.FindAsync(userId);
                            if (user != null)
                            {
                                user.LastActivityTime = DateTime.UtcNow;
                                await dbContext.SaveChangesAsync();
                                _logger.LogDebug("更新用户 {UserId} 的活动时间为 {ActivityTime}", userId, user.LastActivityTime);
                            }
                        }
                        catch (Exception ex)
                        {
                            _logger.LogError(ex, "更新用户活动时间时发生错误，用户ID: {UserId}", userId);
                        }
                    }
                }
                catch (Exception ex)
                {
                    _logger.LogError(ex, "处理用户活动时间更新时发生错误");
                }
            }
        }
    }
} 